
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        serverUrl = 'http://localhost:8080/admin/product/getOss'
		
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};


function get_signature()
{
    // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        body = JSON.parse(body)
        console.log(body);
        var obj = eval ("(" + body['data'] + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{

    suffix = get_suffix(filename)
    g_object_name = key + random_string(10)+ new Date().getTime() + suffix
    return ''
}
function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
    console.log("-------");
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    console.log(new_multipart_params);

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
    console.log("++++++000055");
    up.start();
}

var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
    multi_selection: false,
	container: document.getElementById('oss-container'),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',

    filters: {
        mime_types : [ //只允许上传图片和视频
        { title : "Image files", extensions : "jpg,gif,png,bmp,jpeg" },
        { title : "Video files", extensions : "avi,wmv,mpeg,mp4,mov,mkv,flv,f4v,m4v,rmvb,rm,3gp,dat,ts,mts,vob" }
        ],
        max_file_size : '200mb', //最大只能上传200mb的文件
        prevent_duplicates : true //不允许选取重复文件
    },

	init: {
		PostInit: function() {
			document.getElementById('postfiles').onclick = function() {
			    console.log("点击上传")
                if(uploader.files.length === 0){
                    showMsg("请上传照片或视频！");
                }else{
                    set_upload_param(uploader, '', false);
                }
            return false;
			};
		},

		FilesAdded: function(up, files) {
		    console.log("选择了文件");
			plupload.each(files, function(file) {
			    //删除之前上传的文件，只保留一个
                for (var i = 0; i < up.files.length; i++) {
                    console.log(up.files[i]);
                    if(up.files[i] !== file){
                        up.removeFile(up.files[i]);
                    }
                }
                getImgInfo(file.getNative(),function(time){
                    app.shootTime = time;
                    console.log(app.shootTime);
                });

                //获取文件路径做预览
                app.showUrl = getFileUrl(file.getNative());
			    if(file.type.indexOf("image") === 0){
			        app.type = 0;
                }else{
                    app.type = 1;
                }
			});
		},

		BeforeUpload: function(up, file) {
            console.log("上传前："+file.name);
           set_upload_param(up, file.name, true);
        },

		UploadProgress: function(up, file) {
            console.log("上传中："+file.percent);
            updateProcess(file.percent);
		},

		FileUploaded: function(up, file, info) {
            console.log("上传完成："+info);
            if (info.status == 200)
            {
                uploadOver(true,g_object_name);
            }
            else if (info.status == 203)
            {
                uploadOver(true,g_object_name);
            }
            else
            {
                uploadOver(false,info.response);
            } 
		},

		Error: function(up, err) {
		    console.log("上传错误");
            if (err.code == -600) {
                uploadOver(false,"选择的文件不能超过200mb");
            }
            else if (err.code == -601) {
                uploadOver(false,"请选择图片或视频");
            }
            else if (err.code == -602) {
                uploadOver(false,"这个文件已经上传过一遍了");
            }
            else 
            {
                uploadOver(false, err.response);

            }
		}
	}
});

uploader.init();
